var $clueReceiveTable = $('#clue_receive_list_table');
var $clueReturnTable = $('#clue_return_list_table');
var $clueFollowTable = $('#clue_follow_list_table');
var $clueVisitTable = $('#clue_visit_list_table');
var $contactsListTable = $('#contacts_list_table');

//防止表头与表格不对齐
$(window).resize(function () {
    $clueReceiveTable.bootstrapTable('resetView');
    $clueReturnTable.bootstrapTable('resetView');
    $clueFollowTable.bootstrapTable('resetView');
    $clueVisitTable.bootstrapTable('resetView');
    $contactsListTable.bootstrapTable('resetView');
});

$(function () {
    $('#saveBtn').css('display', 'none');
    $('#editContent').css('display', 'none');
    $('#receiveContent').css('display', 'block');
    $('#returnContent').css('display', 'none');
    $('#followUpContent').css('display', 'none');
    $('#visitContent').css('display', 'none');
    $('#contactsContent').css('display', 'none');
    $('#companyContent').css('display', 'none');
    //注册时间
    $("#registrationTime").datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });
    selectClueReceiveTabList();
    $("#tagBox").html('');
    $("#tagBox").append('<input type="text" name="staticPath" value="" id="staticPath2"/>');
    $("#staticPath2").val('');
    $("#staticPath2").val($("#tagMark").text().split(','));
    WS({
        el: "#staticPath2",
    });
});

function edit() {

    let cityId = $('#cityId').val();// 市id

    let provinceId = '';        // 省id
    let provinceName = '';      // 省名称

    // 新建省市对象(不包含县)
    let newCityJson = {};
    $.each(cityJson, function (key, value) {
        if (key.length <= 8) {
            newCityJson[key] = value;
        }
    });

    // 获取市对应的省份id
    $.each(newCityJson, function (aKey, aValue) {
        $.each(aValue, function (key, value) {
            if (cityId === key) {
                provinceId = aKey.substring(2);
                // console.log('省份id：' + provinceId, '市id：' + cityId, '市名：' + value)
            }
        })
    });
    // 根据省份id获取省份名称
    for (let key in newCityJson[0]) {
        if (key === provinceId) {
            // console.log(newCityJson[0][key]);
            provinceName = newCityJson[0][key];
            break;
        }
    }
    getProvince(provinceId);

    $('#province').find('option[value="' + provinceId + '"]').prop('selected', true);
    $('#city').find('option[value="' + cityId + '"]').prop('selected', true);

    $('#editBtn').css('display', 'none');
    $('#showContent').css('display', 'none');
    $('#saveBtn').css('display', 'block');
    $('#editContent').css('display', 'inline-block');
    var sex =$('#sexId').val();
    if(sex){
        if(sex == 0){
            $("#sex_male").attr("checked","checked");
        } else if(sex == 1) {
            $("#sex_female").attr("checked","checked");
        }
    }
}

/**
 * 弹窗城市选择
 * */
// 渲染城市列表
function getProvince(id) {
    let provinceNames = [];
    $.each(cityJson[0], function (key, value) {
        provinceNames.push('<option value="' + key + '">' + value + '</option>')
    });
    $('#province').html(provinceNames.join(''));
    getCity(id)
}
// 根据省获取市
function getCity(provinceId) {
    $('#city').html('');
    let key = '0,' + provinceId;
    let cityNames = [];
    if(cityJson[key]){
        $.each(cityJson[key], function (key, value) {
            cityNames.push('<option value="' + key + '">' + value + '</option>')
        });
    }
    $('#city').html(cityNames.join(''));

}

// '切换城市'
function changeCity() {
    getCity($('#province').val())
}

function changeTable(str) {
    if (str == 'receive') {
        $('#receive').addClass('active');
        $('#receive').siblings().removeClass('active');
        $('#receiveContent').css('display', 'block');
        $('#returnContent').css('display', 'none');
        $('#followUpContent').css('display', 'none');
        $('#visitContent').css('display', 'none');
        $('#contactsContent').css('display', 'none');
        $('#companyContent').css('display', 'none');
        selectClueReceiveTabList();
    }
    if (str == 'return') {
        $('#return').addClass('active');
        $('#return').siblings().removeClass('active');
        $('#receiveContent').css('display', 'none');
        $('#returnContent').css('display', 'block');
        $('#followUpContent').css('display', 'none');
        $('#visitContent').css('display', 'none');
        $('#contactsContent').css('display', 'none');
        $('#companyContent').css('display', 'none');
        selectClueReturnTabList();
    }
    if (str == 'followUp') {
        $('#followUp').addClass('active');
        $('#followUp').siblings().removeClass('active');
        $('#receiveContent').css('display', 'none');
        $('#returnContent').css('display', 'none');
        $('#followUpContent').css('display', 'block');
        $('#visitContent').css('display', 'none');
        $('#contactsContent').css('display', 'none');
        $('#companyContent').css('display', 'none');
        selectClueFollowTabList();
    }
    if (str == 'visit') {
        $('#visit').addClass('active');
        $('#visit').siblings().removeClass('active');
        $('#receiveContent').css('display', 'none');
        $('#returnContent').css('display', 'none');
        $('#followUpContent').css('display', 'none');
        $('#visitContent').css('display', 'block');
        $('#contactsContent').css('display', 'none');
        $('#companyContent').css('display', 'none');
        selectVisitTabList();
    }
    if (str == 'contacts') {
        $('#contacts').addClass('active');
        $('#contacts').siblings().removeClass('active');
        $('#receiveContent').css('display', 'none');
        $('#returnContent').css('display', 'none');
        $('#followUpContent').css('display', 'none');
        $('#visitContent').css('display', 'none');
        $('#contactsContent').css('display', 'block');
        $('#companyContent').css('display', 'none');
        selectContactsList();
    }
    if (str == 'company') {
        $('#company').addClass('active');
        $('#company').siblings().removeClass('active');
        $('#receiveContent').css('display', 'none');
        $('#returnContent').css('display', 'none');
        $('#followUpContent').css('display', 'none');
        $('#visitContent').css('display', 'none');
        $('#contactsContent').css('display', 'none');
        $('#companyContent').css('display', 'block');
    }
}

/**
 * 领取记录tab页列表信息
 */
function selectClueReceiveTabList(){
    //先销毁表格
    $clueReceiveTable.bootstrapTable('destroy');

    $clueReceiveTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        //请求地址
        url: '/clue/selectClueReceiveList',
        //请求方式
        method: 'post',
        //请求内容类型
        contentType: "application/x-www-form-urlencoded",
        //数据类型
        dataType: "json",
        //是否显示行间隔色
        striped: true,
        //是否启用排序
        sortable: true,
        //排序方式
        sortOrder: "desc",
        sortName: 'receiveTm',
        //是否使用缓存
        cache: false,
        //每行的唯一标识
        uniqueId: "id",
        //显示隐藏列
        showColumns: false,
        //显示刷新按钮
        showRefresh: false,
        //切换显示样式
        showToggle: false,
        //显示Table脚部
        showFooter: false,
        //是否显示分页
        pagination: true,
        //是否显示分页按钮
        showPaginationSwitch: false,
        //是否启用点击选中行
        clickToSelect: false,
        singleSelect: false,
        //最少要显示的列数
        minimumCountColumns: 2,
        //cell没有值时显示
        undefinedText: '',
        //分页方式：client客户端分页，server服务端分页
        sidePagination: "server",
        uniqueId: 'clueReceiveId',
        idField: 'clueReceiveId',
        //每页的记录行数
        pageSize: 5,
        //初始化加载第1页，默认第1页
        pageNumber: 1,
        //可供选择的每页的行数
        pageList: "[10, 20, 50]",
        //查询参数
        queryParams: queryParams,
        columns: [
            {title: '主键', field: 'clueReceiveId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'middle', formatter: indexFormat},
            {title: '领取人',field: 'receivePeopleName',align: 'center', valign: 'middle'},
            {title: '领取时间', field: 'receiveTm', align: 'center', valign: 'middle'},
            {title: '领取方式', field: 'receiveWay', align: 'center', valign: 'middle',formatter: receiveWayFormat}
            ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip(); // 加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        }, formatNoMatches: function () {
            return '无符合条件的记录';
        }
    });
}

/**
 * 领取方式：1-领取；2:分配
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function receiveWayFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "";
    } else if (1 == value) {
        return "领取";
    } else if (2 == value) {
        return "分配";
    }
}

/**
 * 退回记录tab页列表信息
 */
function selectClueReturnTabList(){
    //先销毁表格
    $clueReturnTable.bootstrapTable('destroy');

    $clueReturnTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        //请求地址
        url: '/clue/selectClueReturnList',
        //请求方式
        method: 'post',
        //请求内容类型
        contentType: "application/x-www-form-urlencoded",
        //数据类型
        dataType: "json",
        //是否显示行间隔色
        striped: true,
        //是否启用排序
        sortable: true,
        //排序方式
        sortOrder: "desc",
        sortName: 'returnTm',
        //是否使用缓存
        cache: false,
        //每行的唯一标识
        uniqueId: "id",
        //显示隐藏列
        showColumns: false,
        //显示刷新按钮
        showRefresh: false,
        //切换显示样式
        showToggle: false,
        //显示Table脚部
        showFooter: false,
        //是否显示分页
        pagination: true,
        //是否显示分页按钮
        showPaginationSwitch: false,
        //是否启用点击选中行
        clickToSelect: false,
        singleSelect: false,
        //最少要显示的列数
        minimumCountColumns: 2,
        //cell没有值时显示
        undefinedText: '',
        //分页方式：client客户端分页，server服务端分页
        sidePagination: "server",
        uniqueId: 'clueReturnId',
        idField: 'clueReturnId',
        //每页的记录行数
        pageSize: 5,
        //初始化加载第1页，默认第1页
        pageNumber: 1,
        //可供选择的每页的行数
        pageList: "[10, 20, 50]",
        //查询参数
        queryParams: queryParams,
        columns: [
            {title: '主键', field: 'clueId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'middle', formatter: indexFormat},
            {title: '退回人',field: 'returnPeopleName',align: 'center', valign: 'middle'},
            {title: '退回时间', field: 'returnTm', align: 'center', valign: 'middle'},
            {title: '退回原因', field: 'returnReason', align: 'center', valign: 'middle'}
        ],
        responseHandler: function (result) {
            if (result.code == "000000")
            {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        }, formatNoMatches: function () {
            return '无符合条件的记录';
        }
    });
}

/**
 * 跟进记录tab页列表信息
 */
function selectClueFollowTabList(){
    //先销毁表格
    $clueFollowTable.bootstrapTable('destroy');

    $clueFollowTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        //请求地址
        url: '/clue/selectClueFollowList',
        //请求方式
        method: 'post',
        //请求内容类型
        contentType: "application/x-www-form-urlencoded",
        //数据类型
        dataType: "json",
        //是否显示行间隔色
        striped: true,
        //是否启用排序
        sortable: true,
        //排序方式
        sortOrder: "desc",
        sortName: 'followTm',
        //是否使用缓存
        cache: false,
        //每行的唯一标识
        uniqueId: "id",
        //显示隐藏列
        showColumns: false,
        //显示刷新按钮
        showRefresh: false,
        //切换显示样式
        showToggle: false,
        //显示Table脚部
        showFooter: false,
        //是否显示分页
        pagination: true,
        //是否显示分页按钮
        showPaginationSwitch: false,
        //是否启用点击选中行
        clickToSelect: false,
        singleSelect: false,
        //最少要显示的列数
        minimumCountColumns: 2,
        //cell没有值时显示
        undefinedText: '',
        //分页方式：client客户端分页，server服务端分页
        sidePagination: "server",
        uniqueId: 'clueFollowId',
        idField: 'clueFollowId',
        //每页的记录行数
        pageSize: 5,
        //初始化加载第1页，默认第1页
        pageNumber: 1,
        //可供选择的每页的行数
        pageList: "[10, 20, 50]",
        //查询参数
        queryParams: queryParams,
        columns: [
            {title: '主键', field: 'clueFollowId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'middle', formatter: indexFormat},
            {title: '跟进人',field: 'followPeopleName',align: 'center', valign: 'middle'},
            {title: '跟进方式', field: 'followWay', align: 'center', valign: 'middle', formatter: followWayFormat},
            {title: '跟进时间', field: 'followTm', align: 'center', valign: 'middle'},
            {title: '跟进详情', field: 'followDetail',align: 'center', valign: 'middle'},
            {title: '客户意向', field: 'customerIntention', align: 'center', valign: 'middle'},
            {title: '客户质量', field: 'customerQuality', align: 'center', valign: 'middle', formatter: customerQualityFormat},
            {title: '客户其他需求', field: 'customerOtherNeed',align: 'center', valign: 'middle'},
            {title: '线索评分', field: 'clueScore', align: 'center', valign: 'middle'},
            {title: '沟通时长', field: 'communicationTime', align: 'center', valign: 'remark'},
            {title: '意向判断', field: 'intentionJudgment', align: 'center', valign: 'remark'},
            {title: '备注信息', field: 'clueScore', align: 'center', valign: 'remark'}
        ],
        responseHandler: function (result) {
            if (result.code == "000000")
            {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        }, formatNoMatches: function () {
            return '无符合条件的记录';
        }
    });
}

/**
 * 跟进方式：1-电话；2-拜访
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function followWayFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "";
    } else if (1 == value) {
        return "线上电话";
    } else if (2 == value) {
        return "拜访";
    } else if (3 == value) {
        return "微信";
    } else if (4 == value) {
        return "线下电话";
    } else if (5 == value) {
        return "邮箱";
    } else if (6 == value) {
        return "陪访";
    }
}

/**
 * 客户质量:1-优；2:良；3:一般
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function customerQualityFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "";
    } else if (1 == value) {
        return "优";
    } else if (2 == value) {
        return "良";
    } else if (3 == value) {
        return "一般";
    }
}
/**
 * 拜访记录tab页列表信息
 */
function selectVisitTabList(){
    //先销毁表格
    $clueVisitTable.bootstrapTable('destroy');
    $clueVisitTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        //请求地址
        url: '/clue/selectClueVisitList',
        //请求方式
        method: 'post',
        //请求内容类型
        contentType: "application/x-www-form-urlencoded",
        //数据类型
        dataType: "json",
        //是否显示行间隔色
        striped: true,
        //是否启用排序
        sortable: true,
        //排序方式
        sortOrder: "desc",
        sortName: 'updateTm',
        //是否使用缓存
        cache: false,
        //每行的唯一标识
        uniqueId: "id",
        //显示隐藏列
        showColumns: false,
        //显示刷新按钮
        showRefresh: false,
        //切换显示样式
        showToggle: false,
        //显示Table脚部
        showFooter: false,
        //是否显示分页
        pagination: true,
        //是否显示分页按钮
        showPaginationSwitch: false,
        //是否启用点击选中行
        clickToSelect: false,
        singleSelect: false,
        //最少要显示的列数
        minimumCountColumns: 2,
        //cell没有值时显示
        undefinedText: '',
        //分页方式：client客户端分页，server服务端分页
        sidePagination: "server",
        uniqueId: 'clueVisitRecordId',
        idField: 'clueVisitRecordId',
        //每页的记录行数
        pageSize: 5,
        //初始化加载第1页，默认第1页
        pageNumber: 1,
        //可供选择的每页的行数
        pageList: "[10, 20, 50]",
        //查询参数
        queryParams: queryParams,
        columns: [
            {title: '主键', field: 'clueVisitRecordId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'middle', formatter: indexFormat},
            {title: '跟进日期',field: 'createTm',align: 'center', valign: 'middle'},
            {title: '拜访人',field: 'visitRecordPeopleName',align: 'center', valign: 'middle'},
            {title: '拜访目的',field: 'visitPurpose',align: 'center', valign: 'middle'},
            {title: '拜访地址',field: 'visitAddress',align: 'center', valign: 'middle'},
            {title: '联系人',field: 'contactPerson',align: 'center', valign: 'middle'},
            {title: '联系方式',field: 'contactInformation',align: 'center', valign: 'middle'},
            {title: '职务',field: 'contactJob',align: 'center', valign: 'middle'},
            {title: '沟通时长(分)',field: 'communicationTime',align: 'center', valign: 'middle'}
        ],
        responseHandler: function (result) {
            if (result.code == "000000")
            {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        }, formatNoMatches: function () {
            return '无符合条件的记录';
        }
    });
}

/**
 * 联系人记录tab页列表信息
 */
function selectContactsList(){
    //先销毁表格
    $contactsListTable.bootstrapTable('destroy');
    $contactsListTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        //请求地址
        url: '/clue/selectContactsList',
        //请求方式
        method: 'post',
        //请求内容类型
        contentType: "application/x-www-form-urlencoded",
        //数据类型
        dataType: "json",
        //是否显示行间隔色
        striped: true,
        //是否启用排序
        sortable: true,
        //排序方式
        sortOrder: "desc",
        sortName: 'updateTm',
        //是否使用缓存
        cache: false,
        //每行的唯一标识
        uniqueId: "id",
        //显示隐藏列
        showColumns: false,
        //显示刷新按钮
        showRefresh: false,
        //切换显示样式
        showToggle: false,
        //显示Table脚部
        showFooter: false,
        //是否显示分页
        pagination: true,
        //是否显示分页按钮
        showPaginationSwitch: false,
        //是否启用点击选中行
        clickToSelect: false,
        singleSelect: false,
        //最少要显示的列数
        minimumCountColumns: 2,
        //cell没有值时显示
        undefinedText: '',
        //分页方式：client客户端分页，server服务端分页
        sidePagination: "server",
        uniqueId: 'clueContactId',
        idField: 'clueContactId',
        //每页的记录行数
        pageSize: 5,
        //初始化加载第1页，默认第1页
        pageNumber: 1,
        //可供选择的每页的行数
        pageList: "[10, 20, 50]",
        //查询参数
        queryParams: queryParams,
        columns: [
            {title: '主键', field: 'clueContactId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'middle', formatter: indexFormat},
            {title: '姓名', field: 'contactName', align: 'center', valign: 'middle'},
            {title: '联系方式', field: 'contactInformation', align: 'center', valign: 'middle'},
            {title: '职务', field: 'contactJob', align: 'center', valign: 'middle'}
        ],
        responseHandler: function (result) {
            if (result.code == "000000")
            {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        }, formatNoMatches: function () {
            return '无符合条件的记录';
        }
    });
}

/**
 * 拼接表格查询条件参数
 */
function queryParams(params) {
    params.pageSize = params.limit;//分页大小
    params.pageIndex = (params.offset / params.limit) + 1;
    params.clueId = $.trim($('#clueId').val());
    return params;
}

/**
 * --列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}

function editClue(){
    //线索主键
    var clueId = $("#clueId").val();

    //<!--线索池类别(0:个人池;1:私有池;2:分公司公有池;3:全国公有池)-->
    var poolCategory = $("#poolCategory").val();

    if(poolCategory == "0"){
        //线索池id
        var cluePoolPrivateId = $("#poolId").val();
    } else {
        //线索池id
        var cluePoolPublicId = $("#poolId").val();
    }
    //公司名称
    var companyName = $.trim($("#companyName").val());

    //联系人
    var contactPerson = $.trim($("#contactPerson").val());

    //联系电话
    var contactPersonPhone = $.trim($("#contactPersonPhone").val());

    //性别
    var sex = $("input[name='sex']:checked").val();

    //公司邮箱
    var companyEmail = $.trim($("#companyEmail").val());

    //职务
    var job = $.trim($("#job").val());

    //线索评级
    var rating = $('#rating').val();

    //线索来源
    var source = $.trim($("#source").val());

    //客户类别
    var clientCategories = $('#clientCategories').val();

    //客户级别
    var clientLevel = $('#clientLevel').val();

    //社会信用码
    var unifiedSocialCreditCode = $.trim($('#unifiedSocialCreditCode').val());

    //行业
    var industry = $('#industry').val();

    //公司规模
    var companySize = $('#companySize').val();

    //公司网址
    var companyWebsite = $.trim($('#companyWebsite').val());

    //注册号
    var registrationNumber = $.trim($('#registrationNumber').val());

    //组织机构代码
    var organizationCode = $.trim($('#organizationCode').val());

    //公司类型
    var companyType = $('#companyType').val();

    //法定代表人
    var legalRepresentative = $.trim($('#legalRepresentative').val());

    //对外手机
    var enterpriseExternalPhone = $.trim($('#enterpriseExternalPhone').val());

    //对外座机
    var enterpriseExternalLandline = $.trim($('#enterpriseExternalLandline').val());

    //注册资本
    var registeredCapital = $.trim($('#registeredCapital').val());

    //经营范围
    var businessScope = $.trim($('#businessScope').val());

    //注册时间
    var registrationTime = $.trim($('#registrationTime').val());

    //资本类型
    var capitalType = $.trim($('#capitalType').val());

    //企业状态
    var enterpriseState = $('#enterpriseState').val();

    //参保人数
    var insuredNumber =  $.trim($('#insuredNumber').val());

    //微信
    var wechat = $.trim($('#wechat').val());

    //备注
    var remark = $.trim($('#remark').val());

    //工商注册号
    var businessRegistrationNumber = $.trim($('#businessRegistrationNumber').val());

    //实缴资本
    var paidInCapital = $.trim($('#paidInCapital').val());

    //纳税人识别号
    var taxpayerIdentificationNumber = $.trim($('#taxpayerIdentificationNumber').val());

    //登记机关
    var registrationAuthority = $.trim($('#registrationAuthority').val());

    //核准日期
    var approvedDate = $('#approvedDate').val();

    //成立日期
    var establishmentDate = $('#establishmentDate').val();

    //进出口企业代码
    var importAndExportEnterpriseCode = $.trim($('#importAndExportEnterpriseCode').val());

    //企业地址
    var companyAddress = $.trim($('#companyAddress').val());

    //线索标签
    var tagStr = $('.fm-button').text().split(' ').join(',');
    var tagStrNew = tagStr.substring(0, tagStr.lastIndexOf(','))+ tagStr.substring(tagStr.lastIndexOf(',')+1);
    var tag = tagStrNew;


    //省份id
    var provinceId = $('#province').val();

    //省份名称
    var provinceName = $("#province").find("option:selected").text();

    //城市id
    var cityId = $('#city').val();

    //城市名称
    var cityName = $("#city").find("option:selected").text();

    //公司名称为空和长度验证
    if (!companyName) {
        promptInfo("公司名称不能为空!");
        return;
    } else if (companyName.length > 20) {
        promptInfo("公司名称长度不能大于20个字符！");
        return;
    }

    //联系人为空和长度验证
    if (!contactPerson) {
        promptInfo("联系人不能为空!");
        return;
    } else if (contactPerson.length > 50) {
        promptInfo("联系人长度不能大于50个字符！");
        return;
    }

    //联系电话为空和长度验证
    if (!contactPersonPhone) {
        promptInfo("联系电话不能为空!");
        return;
    } else if (contactPersonPhone.length > 20) {
        promptInfo("联系电话长度不能大于20个字符！");
        return;
    }

    //社会信用码为空验证
    if (!unifiedSocialCreditCode) {
        promptInfo("社会信用码不能为空!");
        return;
    } else if (unifiedSocialCreditCode.length > 20||unifiedSocialCreditCode.length <15) {
        promptInfo("社会信用码长度在15-20位以内！");
        return;
    }

    var jsonData = {
        "clueId":clueId,
        "cluePoolPrivateId":cluePoolPrivateId,
        "cluePoolPublicId":cluePoolPublicId,
        "companyName":companyName,
        "contactPerson":contactPerson,
        "contactPersonPhone":contactPersonPhone,
        "sex":sex,
        "companyEmail":companyEmail,
        "job":job,
        "rating":rating,
        "source":source,
        "clientCategories": clientCategories,
        "clientLevel":clientLevel,
        "unifiedSocialCreditCode":unifiedSocialCreditCode,
        "industry":industry,
        "companySize":companySize,
        "companyWebsite":companyWebsite,
        "registrationNumber":registrationNumber,
        "organizationCode":organizationCode,
        "companyType":companyType,
        "legalRepresentative":legalRepresentative,
        "enterpriseExternalPhone":enterpriseExternalPhone,
        "enterpriseExternalLandline":enterpriseExternalLandline,
        "registeredCapital":registeredCapital,
        "businessScope":businessScope,
        "registrationTime":registrationTime,
        "capitalType":capitalType,
        "enterpriseState":enterpriseState,
        "insuredNumber":insuredNumber,
        "wechat":wechat,
        "remark":remark,
        "businessRegistrationNumber":businessRegistrationNumber,
        "paidInCapital":paidInCapital,
        "taxpayerIdentificationNumber":taxpayerIdentificationNumber,
        "registrationAuthority":registrationAuthority,
        "approvedDate":approvedDate,
        "establishmentDate":establishmentDate,
        "importAndExportEnterpriseCode":importAndExportEnterpriseCode,
        "companyAddress":companyAddress,
        "tag":tag,
        "provinceId":provinceId,
        "provinceName":provinceName,
        "cityId":cityId,
        "cityName":cityName,
    };

    var poolId = $("#poolId").val();
    var poolState = $("#poolState").val();
    var defaultMark = $("#defaultMark").val();
    var allocation = $("#allocation").val();
    $.ajax({
        url: '/clue/editClue',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: (function (data) {
            if (data.code == "000000") {
                $.alert({
                    title: '提示',
                    content: '保存成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                window.location.reload();
/*                                var $thisTabs = parent.$('.mt-nav-bar .nav-tabs').find('li.active');
                                var navTab = parent.$multitabs._getNavTab($thisTabs);
                                closeTab(navTab);
                                openTab("线索详情","/front/cluePoolManager/clueDetail?clueId=" + clueId +"&poolId="
                                    + poolId +"&poolCategory=" + poolCategory +"&poolState=" + poolState
                                    +"&defaultMark=" + defaultMark +"&allocation=" + allocation);*/
                                $('#editBtn').css('display', 'block');
                                $('#showContent').css('display', 'flex');
                                $('#saveBtn').css('display', 'none');
                                $('#editContent').css('display', 'none');
                            }
                        }
                    }
                });
            } else if(data.code == "C00020"){
                $.alert("保存失败，联系电话和社会信用码已存在！");
            } else {
                $.alert("保存失败");
            }
        }),
        error: (function (res) {
            $.alert("保存异常");
        })
    });
}

// 新增联系人弹框
function addPeople() {
    //联系人姓名
    $("#contact_name").val('');
    //职务
    $("#contact_job").val('');
    //联系方式
    $("#contact_information").val('');
    $("#peopleModel").modal("show");
}

// 新增联系人
function insertPeople() {
    //联系人姓名
    var contactName = $("#contact_name").val();
    //职务
    var contactJob = $("#contact_job").val();
    //联系方式
    var contactInformation = $("#contact_information").val();
    //线索id
    var clueId = $.trim($('#clueId').val());

    //联系人姓名为空和长度验证
    if (!contactName) {
        ok = false;
        promptInfo("联系人姓名不能为空!");
        return;
    } else {
        if (contactName.length > 10) {
            ok = false;
            promptInfo("联系人姓名长度不能大于10个字！");
            return;
        }
    }
    //联系方式为空验证
    if (!contactInformation) {
        ok = false;
        promptInfo("联系方式不能为空!");
        return;
    }
    var jsonData = {
        contactName: contactName,
        contactJob: contactJob,
        contactInformation: contactInformation,
        clueId: clueId
    };
    $.ajax({
        url: '/clueContact/save/clueContact',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: (function (data) {
            if (data.code == "000000") {
                $.alert("保存成功！");
                $("#peopleModel").modal("hide");
                $contactsListTable.bootstrapTable('refresh');
            }else {
                alert("保存失败");
            }
        }),
        error: (function () {
            alert("失败");
        })
    });
}

function promptInfo(content) {
    $.alert({
        title: '温馨提示',
        content: content,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary'
            }
        }
    });
}